'use client'

import { useState, useEffect } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Skeleton } from '@/components/ui/skeleton'
import { 
  ArrowLeft, 
  User, 
  Calendar, 
  Clock, 
  CheckSquare, 
  MessageSquare,
  Paperclip,
  Edit,
  Trash2,
  AlertCircle,
  MoreHorizontal,
  Activity,
  Timer
} from 'lucide-react'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'

interface TaskDetail {
  id: string
  title: string
  description?: string
  type: string
  priority: string
  status: string
  estimate?: number
  spent: number
  dueDate?: string
  createdAt: string
  updatedAt: string
  project: {
    id: string
    name: string
    key: string
  }
  iteration?: {
    id: string
    name: string
  }
  requirement?: {
    id: string
    title: string
    type: string
  }
  creator: {
    id: string
    name?: string
    username: string
    email?: string
  }
  assignee?: {
    id: string
    name?: string
    username: string
    email?: string
  }
  comments: Array<{
    id: string
    content: string
    author: {
      name?: string
      username: string
    }
    createdAt: string
  }>
  attachments: Array<{
    id: string
    filename: string
    size: number
    mimeType: string
    createdAt: string
  }>
  _count: {
    comments: number
    attachments: number
  }
}

export function TaskDetail() {
  const params = useParams()
  const router = useRouter()
  const taskId = params.id as string
  const [task, setTask] = useState<TaskDetail | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (taskId) {
      fetchTaskDetail()
    }
  }, [taskId])

  const fetchTaskDetail = async () => {
    setLoading(true)
    try {
      const response = await fetch(`/api/tasks/${taskId}`)
      if (response.ok) {
        const data = await response.json()
        setTask(data)
      } else {
        console.error('Error fetching task detail')
        router.push('/tasks')
      }
    } catch (error) {
      console.error('Error fetching task detail:', error)
      router.push('/tasks')
    } finally {
      setLoading(false)
    }
  }

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      todo: 'bg-gray-100 text-gray-800',
      in_progress: 'bg-yellow-100 text-yellow-800',
      completed: 'bg-green-100 text-green-800',
      cancelled: 'bg-red-100 text-red-800'
    }
    return colors[status] || 'bg-gray-100 text-gray-800'
  }

  const getTypeColor = (type: string) => {
    const colors: Record<string, string> = {
      FEATURE: 'bg-purple-100 text-purple-800',
      BUG: 'bg-red-100 text-red-800',
      IMPROVEMENT: 'bg-blue-100 text-blue-800',
      MAINTENANCE: 'bg-orange-100 text-orange-800',
      RESEARCH: 'bg-indigo-100 text-indigo-800'
    }
    return colors[type] || 'bg-gray-100 text-gray-800'
  }

  const getPriorityColor = (priority: string) => {
    const colors: Record<string, string> = {
      low: 'bg-gray-100 text-gray-800',
      medium: 'bg-yellow-100 text-yellow-800',
      high: 'bg-orange-100 text-orange-800',
      urgent: 'bg-red-100 text-red-800'
    }
    return colors[priority] || 'bg-gray-100 text-gray-800'
  }

  const getTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      FEATURE: '功能',
      BUG: '缺陷',
      IMPROVEMENT: '改进',
      MAINTENANCE: '维护',
      RESEARCH: '研究'
    }
    return labels[type] || type
  }

  const getStatusLabel = (status: string) => {
    const labels: Record<string, string> = {
      todo: '待办',
      in_progress: '进行中',
      completed: '已完成',
      cancelled: '已取消'
    }
    return labels[status] || status
  }

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="flex items-center space-x-4">
          <Button variant="ghost" size="icon">
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <Skeleton className="h-8 w-64 mb-2" />
            <Skeleton className="h-4 w-96" />
          </div>
        </div>
        
        <div className="grid gap-6 md:grid-cols-3">
          {[1, 2, 3].map((i) => (
            <Card key={i}>
              <CardHeader className="pb-2">
                <Skeleton className="h-4 w-20" />
              </CardHeader>
              <CardContent>
                <Skeleton className="h-8 w-12" />
              </CardContent>
            </Card>
          ))}
        </div>

        <div className="grid gap-6">
          <Card>
            <CardHeader>
              <Skeleton className="h-6 w-32" />
            </CardHeader>
            <CardContent>
              <Skeleton className="h-32 w-full" />
            </CardContent>
          </Card>
        </div>
      </div>
    )
  }

  if (!task) {
    return (
      <div className="text-center py-12">
        <AlertCircle className="mx-auto h-12 w-12 text-gray-400 mb-4" />
        <h3 className="text-lg font-medium text-gray-900 mb-2">任务未找到</h3>
        <p className="text-gray-500 mb-4">请检查任务ID是否正确</p>
        <Button onClick={() => router.push('/tasks')}>
          <ArrowLeft className="h-4 w-4 mr-2" />
          返回任务列表
        </Button>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 页面头部 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <Button variant="ghost" size="icon" onClick={() => router.back()}>
            <ArrowLeft className="h-4 w-4" />
          </Button>
          <div>
            <div className="flex items-center space-x-2 mb-2">
              <Badge className={getTypeColor(task.type)}>
                {getTypeLabel(task.type)}
              </Badge>
              <Badge className={getPriorityColor(task.priority)}>
                {task.priority}
              </Badge>
              <Badge className={getStatusColor(task.status)}>
                {getStatusLabel(task.status)}
              </Badge>
            </div>
            <h1 className="text-3xl font-bold tracking-tight">{task.title}</h1>
            <div className="flex items-center space-x-4 mt-2 text-sm text-gray-500">
              <span>项目: {task.project.name} ({task.project.key})</span>
              {task.iteration && (
                <span>迭代: {task.iteration.name}</span>
              )}
              {task.dueDate && (
                <span className="flex items-center space-x-1">
                  <Calendar className="h-3 w-3" />
                  <span>截止: {new Date(task.dueDate).toLocaleDateString('zh-CN')}</span>
                </span>
              )}
            </div>
          </div>
        </div>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="outline" size="icon">
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem>
              <Edit className="h-4 w-4 mr-2" />
              编辑任务
            </DropdownMenuItem>
            <DropdownMenuItem className="text-red-600">
              <Trash2 className="h-4 w-4 mr-2" />
              删除任务
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>

      {/* 统计卡片 */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">预估工时</CardTitle>
            <Timer className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{task.estimate || 0}</div>
            <p className="text-xs text-muted-foreground">
              小时
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">已用工时</CardTitle>
            <Clock className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{task.spent}</div>
            <p className="text-xs text-muted-foreground">
              小时
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">评论</CardTitle>
            <MessageSquare className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{task._count.comments}</div>
            <p className="text-xs text-muted-foreground">
              评论数量
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">附件</CardTitle>
            <Paperclip className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{task._count.attachments}</div>
            <p className="text-xs text-muted-foreground">
              附件数量
            </p>
          </CardContent>
        </Card>
      </div>

      {/* 详细信息标签页 */}
      <Tabs defaultValue="details" className="w-full">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="details">详细信息</TabsTrigger>
          <TabsTrigger value="progress">进度</TabsTrigger>
          <TabsTrigger value="comments">评论</TabsTrigger>
          <TabsTrigger value="attachments">附件</TabsTrigger>
        </TabsList>

        <TabsContent value="details" className="space-y-6">
          <div className="grid gap-6 md:grid-cols-2">
            <Card>
              <CardHeader>
                <CardTitle>基本信息</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">任务类型</span>
                  <Badge className={getTypeColor(task.type)}>
                    {getTypeLabel(task.type)}
                  </Badge>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">优先级</span>
                  <Badge className={getPriorityColor(task.priority)}>
                    {task.priority}
                  </Badge>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">状态</span>
                  <Badge className={getStatusColor(task.status)}>
                    {getStatusLabel(task.status)}
                  </Badge>
                </div>
                {task.estimate !== undefined && (
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">预估工时</span>
                    <span className="text-sm">{task.estimate} 小时</span>
                  </div>
                )}
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">已用工时</span>
                  <span className="text-sm">{task.spent} 小时</span>
                </div>
                {task.dueDate && (
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">截止日期</span>
                    <span className="text-sm">
                      {new Date(task.dueDate).toLocaleDateString('zh-CN')}
                    </span>
                  </div>
                )}
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">创建时间</span>
                  <span className="text-sm text-gray-600">
                    {new Date(task.createdAt).toLocaleDateString('zh-CN')}
                  </span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">更新时间</span>
                  <span className="text-sm text-gray-600">
                    {new Date(task.updatedAt).toLocaleDateString('zh-CN')}
                  </span>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>关联信息</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">所属项目</span>
                  <Badge variant="outline">{task.project.name}</Badge>
                </div>
                {task.iteration && (
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">所属迭代</span>
                    <Badge variant="outline">{task.iteration.name}</Badge>
                  </div>
                )}
                {task.requirement && (
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">关联需求</span>
                    <div className="flex items-center space-x-2">
                      <Badge className={getTypeColor(task.requirement.type)}>
                        {getTypeLabel(task.requirement.type)}
                      </Badge>
                      <span className="text-sm font-medium truncate max-w-[200px]">
                        {task.requirement.title}
                      </span>
                    </div>
                  </div>
                )}
                <div className="flex items-center justify-between">
                  <span className="text-sm font-medium">创建者</span>
                  <div className="flex items-center space-x-2">
                    <div className="h-6 w-6 rounded-full bg-gray-300 flex items-center justify-center">
                      <span className="text-xs font-medium text-gray-700">
                        {(task.creator.name || task.creator.username || 'U').charAt(0).toUpperCase()}
                      </span>
                    </div>
                    <span className="text-sm">
                      {task.creator.name || task.creator.username}
                    </span>
                  </div>
                </div>
                {task.assignee && (
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium">指派人</span>
                    <div className="flex items-center space-x-2">
                      <div className="h-6 w-6 rounded-full bg-gray-300 flex items-center justify-center">
                        <span className="text-xs font-medium text-gray-700">
                          {(task.assignee.name || task.assignee.username || 'U').charAt(0).toUpperCase()}
                        </span>
                      </div>
                      <span className="text-sm">
                        {task.assignee.name || task.assignee.username}
                      </span>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>

          {task.description && (
            <Card>
              <CardHeader>
                <CardTitle>任务描述</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="prose prose-sm max-w-none">
                  <p className="whitespace-pre-wrap">{task.description}</p>
                </div>
              </CardContent>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="progress" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>任务进度</CardTitle>
              <CardDescription>
                任务的工时统计和进度跟踪
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-6">
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium">预估工时</span>
                      <span className="text-sm font-bold">{task.estimate || 0} 小时</span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium">已用工时</span>
                      <span className="text-sm font-bold">{task.spent} 小时</span>
                    </div>
                    {task.estimate && task.estimate > 0 && (
                      <div className="space-y-2">
                        <div className="flex items-center justify-between">
                          <span className="text-sm font-medium">完成进度</span>
                          <span className="text-sm font-bold">
                            {Math.min(100, Math.round((task.spent / task.estimate) * 100))}%
                          </span>
                        </div>
                        <div className="w-full bg-gray-200 rounded-full h-2">
                          <div 
                            className="bg-blue-600 h-2 rounded-full" 
                            style={{ width: `${Math.min(100, Math.round((task.spent / task.estimate) * 100))}%` }}
                          ></div>
                        </div>
                      </div>
                    )}
                  </div>
                  
                  <div className="space-y-2">
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium">剩余工时</span>
                      <span className="text-sm font-bold">
                        {Math.max(0, (task.estimate || 0) - task.spent)} 小时
                      </span>
                    </div>
                    {task.dueDate && (
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">剩余天数</span>
                        <span className="text-sm font-bold">
                          {Math.max(0, Math.ceil((new Date(task.dueDate).getTime() - new Date().getTime()) / (1000 * 60 * 60 * 24)))} 天
                        </span>
                      </div>
                    )}
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium">任务状态</span>
                      <Badge className={getStatusColor(task.status)}>
                        {getStatusLabel(task.status)}
                      </Badge>
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="comments" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <MessageSquare className="h-5 w-5" />
                <span>评论</span>
                <Badge variant="secondary">{task.comments.length}</Badge>
              </CardTitle>
              <CardDescription>
                任务的讨论和评论
              </CardDescription>
            </CardHeader>
            <CardContent>
              {task.comments.length === 0 ? (
                <div className="text-center py-8">
                  <MessageSquare className="mx-auto h-12 w-12 text-gray-400 mb-4" />
                  <p className="text-gray-500">暂无评论</p>
                </div>
              ) : (
                <div className="space-y-4">
                  {task.comments.map((comment) => (
                    <div key={comment.id} className="p-4 border rounded-lg">
                      <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center space-x-2">
                          <div className="h-6 w-6 rounded-full bg-gray-300 flex items-center justify-center">
                            <span className="text-xs font-medium text-gray-700">
                              {(comment.author.name || comment.author.username || 'U').charAt(0).toUpperCase()}
                            </span>
                          </div>
                          <span className="text-sm font-medium">
                            {comment.author.name || comment.author.username}
                          </span>
                        </div>
                        <span className="text-xs text-gray-500">
                          {new Date(comment.createdAt).toLocaleDateString('zh-CN')} {new Date(comment.createdAt).toLocaleTimeString('zh-CN')}
                        </span>
                      </div>
                      <p className="text-sm text-gray-700 whitespace-pre-wrap">{comment.content}</p>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="attachments" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Paperclip className="h-5 w-5" />
                <span>附件</span>
                <Badge variant="secondary">{task.attachments.length}</Badge>
              </CardTitle>
              <CardDescription>
                任务的相关附件和文档
              </CardDescription>
            </CardHeader>
            <CardContent>
              {task.attachments.length === 0 ? (
                <div className="text-center py-8">
                  <Paperclip className="mx-auto h-12 w-12 text-gray-400 mb-4" />
                  <p className="text-gray-500">暂无附件</p>
                </div>
              ) : (
                <div className="space-y-4">
                  {task.attachments.map((attachment) => (
                    <div key={attachment.id} className="flex items-center justify-between p-4 border rounded-lg">
                      <div className="flex items-center space-x-3">
                        <Paperclip className="h-5 w-5 text-gray-400" />
                        <div>
                          <h4 className="font-medium">{attachment.filename}</h4>
                          <p className="text-sm text-gray-500">
                            {(attachment.size / 1024).toFixed(2)} KB • {attachment.mimeType}
                          </p>
                        </div>
                      </div>
                      <div className="text-right">
                        <p className="text-sm text-gray-500">
                          {new Date(attachment.createdAt).toLocaleDateString('zh-CN')}
                        </p>
                        <Button variant="outline" size="sm" className="mt-1">
                          下载
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}